<html>
<head>
<title>Learning backbone.js</title>
<!--
___ require.js ___
A module is different from a traditional script file in that it defines a well-scoped object that avoids polluting the global namespace. It can explicitly list its dependencies and get a handle on those dependencies without needing to refer to global objects, but instead receive the dependencies as arguments to the function that defines the module. Modules in RequireJS are an extension of the Module Pattern, with the benefit of not needing globals to refer to other modules.
The RequireJS syntax for modules allows them to be loaded as fast as possible, even out of order, but evaluated in the correct dependency order, and since global variables are not created, it makes it possible to load multiple versions of a module in a page.
-->
<script data-main="scripts/main" src="./scripts/require.js"></script>
<script src="./scripts/jquery-2.0.3.js"></script>
<script src="./scripts/underscore.js"></script>
<script src="./scripts/backbone.js"></script>
<script type="text/javascript">

Account = Backbone.Model.extend({
    // having only url will cause delete to not use the id; weird
    urlRoot: '/acct',
    defaults: {
        'who': 'temp',
        'age': -1,
        'balance': -1,
    },
    initialize: function() {
        this.on('change:who', function(model) {
            var old = model.previous('who');
        });
    },
    doubleBalance: function() {
        var old = this.get('balance');
        this.set('balance', old * 2);
    },
});

Bank = Backbone.Collection.extend({
    // this has to be url and not urlRoot weird again
    url: '/acct',
    model: Account,
});

var acct = null;
var bank = new Bank();
bank.on('change', function(){
    var totalAge = 0;
    var totalBalance = 0;
    _.each(bank.models, function(ele, index, list) {
        totalAge += parseInt(ele.get('age'),10);
        totalBalance += parseInt(ele.get('balance'),10);
    });
    document.getElementById('numAccts').innerHTML = bank.length;
    document.getElementById('avgAgeAccts').innerHTML = totalAge/bank.length;
    document.getElementById('sumAccts').innerHTML = totalBalance;
});

function createAcct() {
    var w = document.formAcctCreateUpdate.who.value
    var a = document.formAcctCreateUpdate.age.value
    var b = document.formAcctCreateUpdate.balance.value

    acct = new Account({'who': w, 'age': a, 'balance': b});
    acct.save(null, {
        success: function(obj, response, options) {
            clearCreateUpdate();
            bankFetch();
        },
        error: function(obj, response, options) {
            console.log('acct save error')
        }
    });
    /* above line does this for me
    acct.sync('create', acct, {
        success: function(obj, textStatus, jqXHR) {
            acct = new Account(obj);
            console.log(textStatus)
            updateTableAcct();
        },
        error: function(jqXHR, textStatus, errorThrownString) {
            console.log(textStatus + ' ' + errorThrownString)
        }
    });
    */
}
function getSelected() {
    var nodeList = document.formAcctTable['selAcct'];
    var list = Array.prototype.slice.call(nodeList); 
    var closureValue = '';
    _.each(list, function(ele,idx,list) {
        if (ele.checked) {
            closureValue = ele.value;
            return;
        }
    });
    return closureValue;
}

function setUpdateForm() {
    var sel = getSelected();
    var acct = bank.get(sel);
    document.formAcctCreateUpdate.id.value = acct.get('id');
    document.formAcctCreateUpdate.who.value = acct.get('who');
    document.formAcctCreateUpdate.age.value = acct.get('age');
    document.formAcctCreateUpdate.balance.value = acct.get('balance');
}

function clearCreateUpdate() {
    document.formAcctCreateUpdate.id.value = '';
    document.formAcctCreateUpdate.who.value = '';
    document.formAcctCreateUpdate.age.value = '';
    document.formAcctCreateUpdate.balance.value = '';
}

function updateAcct() {
    var w = document.formAcctCreateUpdate.who.value
    var a = document.formAcctCreateUpdate.age.value
    var b = document.formAcctCreateUpdate.balance.value
    var sel = getSelected();
    acct = bank.get(sel);
    acct.set('who', w);
    acct.set('age', a);
    acct.set('balance', b);

    acct.sync('update', acct, {
        success: function(obj, textStatus, jqXHR) {
            updateTableAcct();
            clearCreateUpdate();
        },
        error: function(jqXHR, textStatus, errorThrownString) {
            console.log(textStatus + ' ' + errorThrownString)
        }
    });
}

function deleteAcct() {
    var sel = getSelected();
    bank.get(sel).destroy();
    bankFetch();
    clearCreateUpdate();
}

function bankFetch() {
    bank.fetch({
        success: function(collection, response, options) {
            //console.log('bank fetch success')
            updateTableAcct();
        },
        error: function(collection, response, options) {
            console.log('bank fetch error')
        }
    });
    /* fetch line does this bank = new Bank(obj) for me
    bank.sync('read', bank, {
        success: function(obj, textStatus, jqXHR) {
            bank = new Bank(obj);
            console.log(textStatus)
        },
        error: function(jqXHR, textStatus, errorThrownString) {
            console.log(textStatus + ' ' + errorThrownString)
        }
    }); */
}

function updateTableAcct() {
    var tab = document.getElementById('tableAcctBody');
    var acctsString = '';
    _.each(bank.models, function(ele, index, list) {
        //console.log(index + " " + ele['id']);
        acctsString += '<tr><td><input type="radio" name="selAcct" value="' + ele.get('id') + '" onclick="setUpdateForm()"></input>' + ele.get('id') + '</td><td>' + ele.get('who') + '</td><td>' + ele.get('age') + '</td><td>' + ele.get('balance') + '</td></tr>';
    });
    tab.innerHTML = acctsString;
}


// load the table with existing items from the server
$(document).ready(function() {
    bankFetch();
});
</script>
</head>
<body>
    <form name="formAcctTable">
    <table id="tableAcct" style='border:'>
    <thead>
    <tr><th>id</th><th>who</th><th>age</th><th>balance</th></tr>
    </thead>
    <tfoot id="tableAcctFoot">
    <tr><td><span id="numAccts"></span></td><td></td><td><span id="avgAgeAccts"></span></td><td><span id="sumAccts"></span></td></tr>
    <tr colspan="4"><td></td></tr>
    </tfoot>
    <tbody id="tableAcctBody">
    </tbody>
    </table>
    </form>

    <form name="formAcctCreateUpdate">
    <table>
    <tr><td>id</td><td><input type="text" name="id" disabled></input></td></tr>
    <tr><td>who</td><td><input type="text" name="who"></input></td></tr>
    <tr><td>age</td><td><input type="text" name="age"></input></td></tr>
    <tr><td>balance</td><td><input type="text" name="balance"></input></td></tr>
    <tr><td><button type="button" name="button" onclick="createAcct()">Create</button><button type="button" name="button" onclick="updateAcct()">Update</button><button type="button" name="button" onclick="deleteAcct()">Delete</button><button type="button" name="button" onclick="clearCreateUpdate()">Clear</button></td><td></td></tr>
    </table>
    </form>
</body>
</html>
